﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;

namespace EasyCore.DataValidation
{
    /// <summary>
    /// 禁用内置.net验证功能：继承自.net内置的ValidationVisitor
    /// </summary>
    public class EasyValidationVisitor : ValidationVisitor
    {
        /// <summary>
        /// 是否禁用内置的验证功能
        /// </summary>
        public bool DisableBuiltInModelValidation { get; private set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="actionContext"></param>
        /// <param name="validatorProvider"></param>
        /// <param name="validatorCache"></param>
        /// <param name="metadataProvider"></param>
        /// <param name="validationState"></param>
        /// <param name="disableBuiltInModelValidation"></param>
        public EasyValidationVisitor(ActionContext actionContext, IModelValidatorProvider validatorProvider, ValidatorCache validatorCache, IModelMetadataProvider metadataProvider,
            ValidationStateDictionary? validationState,bool disableBuiltInModelValidation) : base(actionContext, validatorProvider, validatorCache, metadataProvider, validationState)
        {
            DisableBuiltInModelValidation = disableBuiltInModelValidation;
        }

        /// <summary>
        /// 验证方法
        /// </summary>
        /// <param name="metadata"></param>
        /// <param name="key"></param>
        /// <param name="model"></param>
        /// <param name="alwaysValidateAtTopLevel"></param>
        /// <returns></returns>
        public override bool Validate(ModelMetadata? metadata, string? key, object? model, bool alwaysValidateAtTopLevel)
        {
            if (DisableBuiltInModelValidation) return true;//禁用则表示验证通过
            return  base.Validate(metadata, key, model, alwaysValidateAtTopLevel);
        }

        /// <summary>
        /// 验证方法
        /// </summary>
        /// <param name="metadata"></param>
        /// <param name="key"></param>
        /// <param name="model"></param>
        /// <param name="alwaysValidateAtTopLevel"></param>
        /// <param name="container"></param>
        /// <returns></returns>
        public override bool Validate(ModelMetadata? metadata, string? key, object? model, bool alwaysValidateAtTopLevel, object? container)
        {
            if (DisableBuiltInModelValidation) return true;//禁用则表示验证通过
            return base.Validate(metadata, key, model, alwaysValidateAtTopLevel, container);
        }
    }
}
